/*
 * Copyright (c) Jipzingking 2016.
 */

package sdfs.filetree;

import sdfs.namenode.LocatedBlock;

import java.io.Serializable;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class FileNode extends Node implements Serializable, Iterable<BlockInfo> {
    private final List<BlockInfo> blockInfos = new ArrayList<BlockInfo>();
    private int fileSize;
    //file size should be checked when closing the file.

    //now all locatedBlocks are stored in the first blockInfo
    public BlockInfo getMainBlockInfo(){
        if (blockInfos.size()==0)
            blockInfos.add(new BlockInfo());
        if (blockInfos.size()>0)
            return blockInfos.get(0);
        else return null;
    }

    public void addBlockInfo(BlockInfo blockInfo) {
        blockInfos.add(blockInfo);
    }

    public int getBlockAmount(){
        int amount=0;

        for(BlockInfo blocks:blockInfos)
            for (LocatedBlock block:blocks)
                amount++;

        return amount;
    }
//---------------------------------------------------------------------//
    public void removeLastBlockInfo() {
        blockInfos.remove(blockInfos.size() - 1);
    }

    public BlockInfo getLastBlockInfo(){
        return blockInfos.get(blockInfos.size()-1);
    }

    public LocatedBlock getLastLocatedBlock(){
        BlockInfo blockInfo = blockInfos.get(blockInfos.size()-1);
        return blockInfo.getLastLocatedBlock();

    }

    public int getFileSize() {
        return fileSize;
    }

    public void setFileSize(int fileSize) {
        this.fileSize = fileSize;
    }

    @Override
    public Iterator<BlockInfo> iterator() {
        return blockInfos.listIterator();
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        FileNode that = (FileNode) o;

        return blockInfos.equals(that.blockInfos);
    }

    @Override
    public int hashCode() {
        return blockInfos.hashCode();
    }
}

